#include "buzzer.h"
#include "driver/ledc.h"

// LEDC配置
#define LEDC_TIMER         LEDC_TIMER_0
#define LEDC_MODE          LEDC_LOW_SPEED_MODE
#define LEDC_CHANNEL       LEDC_CHANNEL_0
#define LEDC_DUTY          4000 // 占空比，范围为 0 ~ (2^resolution - 1)
#define LEDC_RESOLUTION    LEDC_TIMER_13_BIT

// 静态变量保存蜂鸣器引脚
static int buzzer_pin = -1;

// 初始化蜂鸣器
void buzzer_init(uint32_t pin) {
    buzzer_pin = pin;

    // 配置LEDC定时器
    ledc_timer_config_t ledc_timer = {
        .speed_mode = LEDC_MODE,
        .timer_num = LEDC_TIMER,
        .duty_resolution = LEDC_RESOLUTION,
        .freq_hz = 2000, // 初始频率
        .clk_cfg = LEDC_AUTO_CLK,
    };
    ledc_timer_config(&ledc_timer);

    // 配置LEDC通道
    ledc_channel_config_t ledc_channel = {
        .gpio_num = buzzer_pin,
        .speed_mode = LEDC_MODE,
        .channel = LEDC_CHANNEL,
        .timer_sel = LEDC_TIMER,
        .duty = 0,  // 初始占空比为 0
        .hpoint = 0,
    };
    ledc_channel_config(&ledc_channel);
}

// 设置蜂鸣器频率
void buzzer_set_frequency(uint32_t frequency) {
    ledc_set_freq(LEDC_MODE, LEDC_TIMER, frequency);
}

// 启动蜂鸣器
void buzzer_start(void) {
    ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, LEDC_DUTY);
    ledc_update_duty(LEDC_MODE, LEDC_CHANNEL);
}

// 停止蜂鸣器
void buzzer_stop(void) {
    ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, 0);
    ledc_update_duty(LEDC_MODE, LEDC_CHANNEL);
}
